﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using XmlSeri = System.Xml.Serialization.XmlSerializer;

namespace ArgusLight.Xml.Serialization
{
	public static class XmlSerializer
	{
		public static int Serialize(Stream stream, object obj)
		{
			XmlSeri xs = new XmlSeri(obj.GetType());
			byte[] data;
			using (MemoryStream ms = new MemoryStream())
			{
				xs.Serialize(ms, obj);
				data = new byte[(int)ms.Length];
				ms.Seek(0, SeekOrigin.Begin);
				ms.Read(data, 0, data.Length);
				ms.Close();
			}
			stream.Write(data, 0, data.Length);
			stream.WriteByte((byte)'\0');
			return data.Length;
		}

		public static T Deserialize<T>(Stream stream)
		{
			return (T)Deserialize(stream, typeof(T));
		}

		public static object Deserialize(Stream stream, Type type)
		{
			XmlSeri xs = new XmlSeri(type);

			List<byte> data = new List<byte>();
			while (true)
			{
				int b = stream.ReadByte();
				if (b == -1 || b == '\0')
					break;
				data.Add((byte)b);
			}

			using (MemoryStream ms = new MemoryStream(data.Count))
			{
				byte[] bytes = data.ToArray();
				data = null;
				ms.Write(bytes, 0, bytes.Length);
				ms.Seek(0, SeekOrigin.Begin);
				object RetVal = xs.Deserialize(ms);
				ms.Close();
				return RetVal;
			}
		}
	}
}
